package com.example.demo.interceptor;

import com.example.demo.GlobalException.BizException;
import com.example.demo.GlobalException.CommonEnum;
import com.example.demo.redisToken.RedisToken;
import com.example.demo.util.IPUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author mrc
 * redisToken拦截器
 */
@Component
public class RedisTokenInterceptor extends HandlerInterceptorAdapter {

    RedisToken redisToken;

    @Autowired
    public RedisTokenInterceptor(RedisToken redisToken) {
        this.redisToken = redisToken;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(RedisToken.TOKEN_NAME);

        if (! StringUtils.hasText(token)) {
            throw new BizException(CommonEnum.FORBIDDEN);
        }


        try{
            if (redisToken.isTokenExpired(token)) {
                throw new BizException(CommonEnum.LOGIN_TIME_OUT);
            }

            String reqIp = IPUtils.getIpAddr(request);

            String tokenIp = redisToken.getIpFromToken(request);

            if (! Objects.equals(reqIp, tokenIp)) {
                throw new BizException(CommonEnum.FORBIDDEN);
            }

        } catch (Exception e) {
            throw new BizException(CommonEnum.LOGIN_TIME_OUT);
        }
        return true;
    }
}
